<template>
  <button class="btn-ghost"
    :class="classType"
    :disabled="classType === 'disabled'"
    @click.prevent="onSendMsgCode">
    {{text}}
  </button>
</template>

<script>
import { apiSendMsgCode } from 'js/api'

export default {
  props: {
    time: {
      type: Number,
      default: 60
    },
    isReset: {
      type: Boolean,
      default: false
    },
    // 需验证的手机号是否填
    isPhone: {
      type: String,
      default: ''
    },
    // 来源
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      msgCodeTime: this.time,
      classType: 'code',
      text: '获取验证码'
    }
  },
  methods: {
    /**
     * 生成倒计时
     */
    onStartCountDown() {
      if (!this.isPhone) return
      if (!/^(((13[0-9]{1})|(17[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(14[0-9]{1}))+\d{8})$/.test(this.isPhone)) return
      if (this.msgCodeTime === 0) {
        this.classType = 'code'
        this.text = '获取验证码'
        this.msgCodeTime = this.time
      } else {
        this.classType = 'disabled'
        this.text = `重新发送${this.msgCodeTime}s`
        this.msgCodeTime--
        setTimeout(() => {
          this.onStartCountDown()
        }, 1000)
      }
    },
    /**
     * 获取短信验证码
     */
    onSendMsgCode() {
      this.onStartCountDown()
      // 注册
      if (!this.type || this.type == 'register') {
        apiSendMsgCode.registerCode(this.isPhone).then(data => {
          console.log(data)
        })
      } else {
        // 忘记密码
        apiSendMsgCode.forgotCode(this.isPhone).then(data => {
          console.log(data)
        })
      }
    }
  },
  watch: {
    isReset(newVal, oldVal) {
      if (newVal) {
        this.msgCodeTime = 0
        this.$parent.isReset = false
      }
    }
  }
}
</script>